package com.gitee.wsl.text.parameter

@Suppress("KDocMissingDocumentation")
 interface StringValuesBuilder {
     val caseInsensitiveName: Boolean
     fun getAll(name: String): List<String>?

     operator fun contains(name: String): Boolean
     fun contains(name: String, value: String): Boolean
     fun names(): Set<String>
     fun isEmpty(): Boolean
     fun entries(): Set<Map.Entry<String, List<String>>>

     operator fun set(name: String, value: String)

     operator fun get(name: String): String?
     fun append(name: String, value: String)
     fun appendAll(stringValues: StringValues)
     fun appendMissing(stringValues: StringValues)
     fun appendAll(name: String, values: Iterable<String>)
     fun appendMissing(name: String, values: Iterable<String>)
     fun remove(name: String)
     fun removeKeysWithNoEntries()
     fun remove(name: String, value: String): Boolean
     fun clear()

     fun build(): StringValues
}

@Suppress("KDocMissingDocumentation", "DEPRECATION")
 open class StringValuesBuilderImpl(
    final override val caseInsensitiveName: Boolean = false,
    size: Int = 8
) : StringValuesBuilder {

    protected val values: MutableMap<String, MutableList<String>> =
        if (caseInsensitiveName) caseInsensitiveMap() else LinkedHashMap(size)

    override fun getAll(name: String): List<String>? = values[name]

    override operator fun contains(name: String): Boolean = name in values

    override fun contains(name: String, value: String): Boolean = values[name]?.contains(value) ?: false

    override fun names(): Set<String> = values.keys

    override fun isEmpty(): Boolean = values.isEmpty()

    override fun entries(): Set<Map.Entry<String, List<String>>> = values.entries

    override operator fun set(name: String, value: String) {
        validateValue(value)
        val list = ensureListForKey(name)
        list.clear()
        list.add(value)
    }

    override operator fun get(name: String): String? = getAll(name)?.firstOrNull()

    override fun append(name: String, value: String) {
        validateValue(value)
        ensureListForKey(name).add(value)
    }

    override fun appendAll(stringValues: StringValues) {
        stringValues.forEach { name, values ->
            appendAll(name, values)
        }
    }

    override fun appendMissing(stringValues: StringValues) {
        stringValues.forEach { name, values ->
            appendMissing(name, values)
        }
    }

    override fun appendAll(name: String, values: Iterable<String>) {
        ensureListForKey(name).let { list ->
            values.forEach { value ->
                validateValue(value)
                list.add(value)
            }
        }
    }

    override fun appendMissing(name: String, values: Iterable<String>) {
        val existing = this.values[name]?.toSet() ?: emptySet()

        appendAll(name, values.filter { it !in existing })
    }

    override fun remove(name: String) {
        values.remove(name)
    }

    override fun removeKeysWithNoEntries() {
        for ((k, _) in values.filter { it.value.isEmpty() }) {
            remove(k)
        }
    }

    override fun remove(name: String, value: String): Boolean = values[name]?.remove(value) ?: false

    override fun clear() {
        values.clear()
    }

    override fun build(): StringValues {
        return StringValuesImpl(caseInsensitiveName, values)
    }

    protected open fun validateName(name: String) {
    }

    protected open fun validateValue(value: String) {
    }

    @Suppress("DEPRECATION")
    private fun ensureListForKey(name: String): MutableList<String> {
        return values[name] ?: mutableListOf<String>().also { validateName(name); values[name] = it }
    }
}

/**
 * Append values from [source] filtering values by the specified [predicate]
 * @param keepEmpty when `true` will keep empty lists otherwise keys with no values will be discarded
 */
 fun StringValuesBuilder.appendFiltered(
    source: StringValues,
    keepEmpty: Boolean = false,
    predicate: (String, String) -> Boolean
) {
    source.forEach { name, value ->
        val list = value.filterTo(ArrayList(value.size)) { predicate(name, it) }
        if (keepEmpty || list.isNotEmpty()) {
            appendAll(name, list)
        }
    }
}

/**
 * Append all values from the specified [builder]
 */
 fun StringValuesBuilder.appendAll(builder: StringValuesBuilder): StringValuesBuilder = apply {
    builder.entries().forEach { (name, values) ->
        appendAll(name, values)
    }
}

/**
 * Appends [name] [value] pair if there are no values associated with [name]
 */
 fun StringValuesBuilder.appendIfNameAbsent(name: String, value: String): StringValuesBuilder = apply {
    if (contains(name)) return@apply
    append(name, value)
}

/**
 * Appends [name] [value] pair if there is no existing [name] [value] pair
 */
 fun StringValuesBuilder.appendIfNameAndValueAbsent(name: String, value: String): StringValuesBuilder = apply {
    if (contains(name, value)) return@apply
    append(name, value)
}